package com.itheima.controller;

import com.itheima.service.IChatHistoryService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.function.Consumer;

@RestController
@RequestMapping("/ai/service")
public class ServerChatController {

    @Autowired
    private ChatClient serviceChatClient;
    @Autowired
    private IChatHistoryService chatHistoryService;

    @GetMapping(produces = "text/html;charset=UTF-8")
    public Flux<String> stream(@RequestParam("prompt") String prompt, @RequestParam("chatId") String chatId) {
        chatHistoryService.saveChatHistory("service", chatId);
        return serviceChatClient.prompt(prompt)
                .advisors(new Consumer<ChatClient.AdvisorSpec>() {
                    @Override
                    public void accept(ChatClient.AdvisorSpec advisorSpec) {
                        advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId);
                    }
                })
                .stream().content();
    }
}
